package com.af.monitorModule.controller.live;

import com.af.monitorModule.generator.QualityInspector;
import com.af.monitorModule.generator.entity.*;
import com.af.monitorModule.generator.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author lyz
 */
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/receive")
public class Information {

    @Autowired
    private MonitorService monitorService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private ErrorSendService errorSendService;

    @Autowired
    private ServerService serverService;

    @Autowired
    private ServerPushService serverPushService;

    @Autowired
    private QualityInspector qualityInspector;

    @Autowired
    private ValueOperations<String,Object> valueOperations;

    private static final Logger logger = LoggerFactory.getLogger(Information.class);

    /**
     *
     * @param monitorId 监控ID
     * @param msg 传入的数据json
     * @return 返回
     */
    @PostMapping("/newForward/{monitorId}")
    public String newForward(@PathVariable String monitorId,@RequestBody JSONObject msg){
        Monitor monitor = monitorService.getById(monitorId);
        Company company = companyService.getById(monitor.getCompanyId());
        if (monitor.getState() == 1){
            JSONObject jsonObject = new JSONObject() {{
                put("isText",msg.getBooleanValue("isText"));
                put("isSpeak",msg.getBooleanValue("isSpeak"));
                put("text", msg.get("text").toString());
                put("speak",msg.get("speak").toString());
                put("time", DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalTime.now()));
                put("company", company.getCompanyName());
            }};
            msg.remove("isText");
            msg.remove("isSpeak");
            msg.remove("text");
            msg.remove("speak");
            qualityInspector.inspect(jsonObject);
        }
        return forward(monitorId,msg);
    }


    @PostMapping("/forward/{monitorId}")
    public String forward(@PathVariable String monitorId,@RequestBody JSONObject msg){
        //夜间备份过滤
        if (isFilterBackup(msg)){
            try {
                valueOperations.increment("toDayMeaningless");
            }catch (Exception e){ logger.error("统计过滤无意义推送数量异常----->" + e.getMessage()); }
            return "200";
        }
        //查找对应的监控信息
        Monitor monitor = monitorService.getById(monitorId);
        if (monitor == null){
            return "500";
        }
        if (monitor.getState() != 1){
            return "200";
        }
        //根据监控ID获取对应公司的钉钉群
        Company company = companyService.getById(monitor.getCompanyId());
        //推送到钉钉群消息
        ResponseEntity<String> stringResponseEntity = new RestTemplate().postForEntity(company.getDdGroupLink(), msg, String.class);
        String body = stringResponseEntity.getBody();
        JSONObject resBody ;
        try {
            resBody = JSON.parseObject(body);
        }catch (Exception e){
            logger.error("推送时，返回体转换Json异常----->" + body);
            errorSendService.save(new ErrorSend()
                    .setSendCode(""+stringResponseEntity.getStatusCodeValue())
                    .setSendMonitorId(Integer.parseInt(monitorId))
                    .setSendTime(LocalDateTime.now())
                    .setSendUrl(company.getDdGroupLink())
                    .setSendValue(msg.toJSONString())
                    .setResBody(body));
            return "200";
        }
        //如果推送失败，存入推送错误表
        if (stringResponseEntity.getStatusCodeValue() != 200 || resBody.getInteger("errcode") != 0){
            logger.error("推送完毕后，获得的推送状态异常----->" + body);
            errorSendService.save(new ErrorSend()
                    .setSendCode(""+stringResponseEntity.getStatusCodeValue())
                    .setSendMonitorId(Integer.parseInt(monitorId))
                    .setSendTime(LocalDateTime.now())
                    .setSendUrl(company.getDdGroupLink())
                    .setSendValue(msg.toJSONString())
                    .setResBody(body));
        }else {
            //进入统计
            statistics(msg);
        }
        //始终给监控程序返回200
        return "200";
    }

    @PostMapping("/pushServer/{serverId}")
    public String pushServer(@PathVariable String serverId,@RequestBody JSONObject msg){
        //查找对应的监控信息
        Server server = serverService.getById(serverId);
        if (server == null){
            return "200";
        }
        serverPushService.save(new ServerPush()
                .setServerId(Integer.parseInt(serverId))
                .setCpuCore(msg.getInteger("cpuCore"))
                .setCpuLogic(msg.getInteger("cpuLogic"))
                .setCpuUse(msg.getBigDecimal("cpuUse"))
                .setDiskAll(msg.get("diskAll").toString())
                .setDiskUse(msg.get("diskUse").toString())
                .setDiskFree(msg.get("diskFree").toString())
                .setDiskPercent(msg.get("diskPercent").toString())
                .setMemoryAll(msg.getLong("memoryAll"))
                .setMemoryUse(msg.getLong("memoryUse"))
                .setMemoryFree(msg.getLong("memoryFree"))
                .setMemoryPercent(msg.getBigDecimal("memoryPercent"))
                .setDiskRead(msg.getLong("diskIORead"))
                .setDiskWrite(msg.getLong("diskIOWrite"))
                .setDiskTps(msg.getLong("diskIOTps"))
                .setNetIn(msg.getLong("netIn"))
                .setNetOut(msg.getLong("netOut"))
                .setPushDate(LocalDateTime.now())
        );
        //当日的服务器状态推送+1
        try {
            valueOperations.increment("toDayServerPush");
        }catch (Exception e){ logger.error("统计服务器指标推送数量异常----->" + e.getMessage()); }
        //始终给监控程序返回200
        return "200";
    }


    public boolean isFilterBackup(JSONObject res){
        int hour = LocalTime.now().getHour();
        if (hour>6 && hour < 19){
            return false;
        }
        String text = res.toJSONString();
        return text.contains("BACKUP");
    }

    private void statistics(JSONObject msg){
        String inner = msg.toJSONString();
        //统计推送成功数量
        try {
            valueOperations.increment("toDaySendMSG");
        }catch (Exception e){ logger.error("统计消息推送数量异常----->" + e.getMessage()); }

        //统计自动重启服务数量
        if (inner.contains("已重启")){
            try {
                valueOperations.increment("toDayServiceRestart");
            }catch (Exception e){ logger.error("统计自动重启服务数量异常----->" + e.getMessage()); }
        }

        //统计成功防止数据库死锁次数
        if (inner.contains("已被终止")){
            try {
                valueOperations.increment("toDayKillDataBase");
            }catch (Exception e){ logger.error("统计终止数据库死锁数量异常----->" + e.getMessage()); }
        }
    }
}
